package com.gsmvn.ngamgaixinh;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.appota.congaixinh.model.Comment;
import com.appota.congaixinh.model.Image;
import com.appota.congaixinh.model.Paging;
import com.appota.congaixinh.model.Photo;
import com.appota.congaixinh.model.User;
import com.appota.vn.util.CommonUtils;
import com.facebook.FacebookException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Request.GraphUserCallback;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.facebook.widget.ProfilePictureView;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CommentActivity extends Activity {
	Photo photo;
	String photo_id;
	private ImageLoader imageLoader;
	private DisplayImageOptions options;
	private ImageView imgPhoto;
	private TextView txtLikeCount;
	private TextView txtContent;
	private EditText editText;
	private Button btnComment;
	private ImageView imgLikePost;
	private LinearLayout linearLayout;
	private ProgressBar progressBar;
	int fb_offset = 25;
	UiLifecycleHelper uiLifecycleHelper;
	private AlertDialog dialog;
	protected GraphUser graphUser;
	protected Menu menu;
	private RelativeLayout contentLayout;
	boolean is_user_like;

	@Override
	public void onResume() {
		super.onResume();
		if (graphUser == null) {
			getUserIfvailable();
		}
		uiLifecycleHelper.onResume();
	}

	private void getUserIfvailable() {
		Request requestme = Request.newMeRequest(Session.getActiveSession(),
				new GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// TODO Auto-generated method stub
						Log.e("", "user res " + response);
						if (user != null) {
							graphUser = user;
							onPrepareOptionsMenu(menu);
						}
					}
				});
		RequestAsyncTask asyncTask = new RequestAsyncTask(requestme);
		asyncTask.execute();
	}

	private void initImageLoader() {
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_launcher).cacheInMemory()
				.cacheOnDisc().build();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiLifecycleHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiLifecycleHelper.onDestroy();
	}

	private static final String TRACKER_ID = "UA-37513871-5";
	private Tracker tracker;

	@Override
	public void onStart() {
		super.onStart();
		tracker.sendView("GaiXinhComment");
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiLifecycleHelper.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	private StatusCallback callback = new StatusCallback() {

		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			// TODO Auto-generated method stub
			if (state == SessionState.OPENED) {
				// dialog.dismiss();
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				if (graphUser == null)
					getUserIfvailable();
			}
		}
	};

	private ProgressDialog progressDialog;
	private Integer like_count;
	private TextView txtUserLike;
	private String album_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		if (intent != null) {
			photo_id = intent.getStringExtra("photo_id");
			like_count = Integer.valueOf(intent.getIntExtra("like_count", 0));
			is_user_like = intent.getBooleanExtra("photo_id", false);
			album_id = intent.getStringExtra("album_id");
		}
		initImageLoader();
		initView();
		uiLifecycleHelper = new UiLifecycleHelper(this, callback);
		uiLifecycleHelper.onCreate(savedInstanceState);
	}

	public void showMessageDialog(int title, int msg) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(getResources().getString(title))
				.setMessage(getResources().getString(msg))
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private void initView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.comment_activity);
		tracker = GoogleAnalytics.getInstance(this).getTracker(TRACKER_ID);
		contentLayout = (RelativeLayout) findViewById(R.id.content);
		imgPhoto = (ImageView) findViewById(R.id.img);
		imgLikePost = (ImageView) findViewById(R.id.imgLike);
		txtContent = (TextView) findViewById(R.id.txtContentPoster);
		txtLikeCount = (TextView) findViewById(R.id.txtLikeCount);
		editText = (EditText) findViewById(R.id.edittextComment);
		btnComment = (Button) findViewById(R.id.btnComment);
		linearLayout = (LinearLayout) findViewById(R.id.listComment);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		TextView viewMoreComment = (TextView) findViewById(R.id.moreComment);
		txtUserLike = (TextView) findViewById(R.id.txtUserLike);
		imgLikePost.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!Session.getActiveSession().isOpened()) {
					showLoginFaceBookDialog();
				} else {
					if (CommonUtils.checkNetworkAvaliable(CommentActivity.this)) {
						Log.e("", "photo_id " + photo_id);
						Request request = new Request(Session
								.getActiveSession(), "/" + photo_id + "/likes",
								null, HttpMethod.POST, new Callback() {

									@Override
									public void onCompleted(Response response) {
										// TODO Auto-generated method stub
										Log.e("",
												"res like "
														+ response.toString());
										GraphObject graphObject = response
												.getGraphObject();
										JSONObject json = graphObject
												.getInnerJSONObject();
										Log.e("", "json " + json.toString());
										try {
											boolean state = json
													.getBoolean("FACEBOOK_NON_JSON_RESULT");
											if (state) {
												txtUserLike
														.setVisibility(View.VISIBLE);
												txtLikeCount.setText(like_count
														+ " nguoi khac ");
											}
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
						RequestAsyncTask asyncTask = new RequestAsyncTask(
								request);
						asyncTask.execute();
					} else
						showMessageDialog(R.string.error_connection,
								R.string.error_connection_msg);

				}
			}
		});
		viewMoreComment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (CommonUtils.checkNetworkAvaliable(CommentActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
					Log.e("", "photo id " + photo.getId());
					Log.e("", "photo.getCommentPaging().getNext() "
							+ photo.getCommentPaging().getNext());
					Request request = new Request(null, "/" + photo_id + "/"
							+ photo.getCommentPaging().getNext(), null,
							HttpMethod.GET, new Callback() {

								@Override
								public void onCompleted(Response response) {
									// TODO Auto-generated method stub
									progressBar.setVisibility(View.GONE);
									Log.e("", "res " + response.toString());
									try {
										loadComment(response);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							});
					RequestAsyncTask asyncTask = new RequestAsyncTask(request);
					asyncTask.execute();
				} else
					showMessageDialog(R.string.error_connection,
							R.string.error_connection_msg);

			}
		});
		initCommentsView();
	}

	private void loadComment(Response response) throws JSONException {
		Gson gson = new Gson();
		GraphObject graphObject = response.getGraphObject();
		if (graphObject != null) {
			JSONObject grap = graphObject.getInnerJSONObject();
			JSONObject pagingjson = grap.getJSONObject("paging");
			Paging paging = gson.fromJson(pagingjson.toString(), Paging.class);
			paging.rebbuildPagingCommentString();
			photo.setCommentPaging(paging);
			JSONArray array = grap.getJSONArray("data");
			for (int i = 0; i < array.length(); i++) {
				JSONObject object = array.getJSONObject(i);
				Comment comment = gson.fromJson(object.toString(),
						Comment.class);
				JSONObject object3 = object.getJSONObject("from");
				User user = gson.fromJson(object3.toString(), User.class);
				comment.setUser(user);
				photo.getList_comments().add(comment);
				loadViewComment(comment);
			}
		}
	}

	private void showLoginFaceBookDialog() {
		View view1 = LayoutInflater.from(CommentActivity.this).inflate(
				R.layout.dialog, null);
		LoginButton ok = (LoginButton) view1.findViewById(R.id.authButton);
		ok.setOnErrorListener(new OnErrorListener() {

			@Override
			public void onError(FacebookException error) {
				// TODO Auto-generated method stub
				Toast.makeText(CommentActivity.this, error.toString(), 2000)
						.show();
				Log.e("", error.toString());
			}
		});
		ArrayList<String> per = new ArrayList<String>();
		ArrayList<String> per1 = new ArrayList<String>();
		per1.add("user_photos");
		per.add("publish_stream");

		ok.setPublishPermissions(per);
		AlertDialog.Builder buider = new Builder(CommentActivity.this);
		buider.setTitle(getResources().getString(R.string.pop_up_title))
				.setView(view1);
		dialog = buider.create();
		dialog.show();

	}

	public void postComment(View view) {
		final String strPost = editText.getText().toString();
		Bundle bundle = new Bundle();
		bundle.putString("message", strPost);
		if (!Session.getActiveSession().isOpened()) {
			showLoginFaceBookDialog();
			// make request to the /me API
		} else {
			if (!strPost.equals("") && strPost != null)
				if (CommonUtils.checkNetworkAvaliable(CommentActivity.this)) {
					progressDialog = new ProgressDialog(CommentActivity.this);
					progressDialog.setMessage(getResources().getString(R.string.dangguidulieu));
					progressDialog.show();
					Request request = new Request(Session.getActiveSession(),
							"/" + photo_id + "/comments", bundle,
							HttpMethod.POST, new Callback() {

								@Override
								public void onCompleted(Response response) {
									// TODO Auto-generated method stub
									Log.e("", "post comment response "
											+ response.toString());

									if (response.getError() == null) {
										if (graphUser != null) {
											Comment comment = new Comment();
											SimpleDateFormat format = new SimpleDateFormat(
													"yyyy-MM-dd'T'HH:mm:ssZZZZ");
											comment.setCreated_time(format
													.format(new Date()));
											comment.setMessage(strPost);
											User user1 = new User();
											user1.setName(graphUser.getName());
											user1.setPicture(graphUser
													.getLink());
											comment.setUser(user1);
											comment.setLike_count(0);
											loadViewComment(comment);
											dismissProgressDialog();
										} else {
											Request.executeMeRequestAsync(
													Session.getActiveSession(),
													new GraphUserCallback() {

														@Override
														public void onCompleted(
																GraphUser user,
																Response response) {
															// TODO
															// Auto-generated
															// method
															// stub
															progressDialog
																	.dismiss();
															if (user != null) {
																Comment comment = new Comment();
																SimpleDateFormat format = new SimpleDateFormat(
																		"yyyy-MM-dd'T'HH:mm:ssZZZZ");
																comment.setCreated_time(format
																		.format(new Date()));
																comment.setMessage(strPost);
																User user1 = new User();
																user1.setName(user
																		.getName());
																user1.setPicture(user
																		.getLink());
																comment.setUser(user1);
																comment.setLike_count(0);
																loadViewComment(comment);
																dismissProgressDialog();
															}
														}
													});
										}

									}
								}
							});
					RequestAsyncTask asyncTask = new RequestAsyncTask(request);
					asyncTask.execute();
				} else
					showMessageDialog(R.string.error_connection,
							R.string.error_connection_msg);

		}
	}

	private void initCommentsView() {
		// TODO Auto-generated method stub
		Log.e("", "photo_id " + photo_id);
		if (CommonUtils.checkNetworkAvaliable(this)) {
			showProgressDialog();
			progressDialog.setCancelable(false);
			contentLayout.setVisibility(View.INVISIBLE);
			Request request = new Request(Session.getActiveSession(), "/" + photo_id, null,
					HttpMethod.GET, new Callback() {

						@Override
						public void onCompleted(Response response) {
							// TODO Auto-generated method stub
							initPhoto(response);
						}
					});
			RequestAsyncTask asyncTask = new RequestAsyncTask(request);
			asyncTask.execute();
		} else {
			showMessageDialog(R.string.error_connection,
					R.string.error_connection_msg);
		}

	}

	private void loadViewComment(final Comment comment) {
		View view = LayoutInflater.from(this).inflate(R.layout.comment_item,
				null);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.setMargins(10, 5, 10, 5);
		view.setLayoutParams(layoutParams);
		ProfilePictureView userprofile = (ProfilePictureView) view
				.findViewById(R.id.profileUser);
		TextView txtUser = (TextView) view.findViewById(R.id.txtUser);
		TextView txtComment = (TextView) view.findViewById(R.id.txtContent);
		final TextView txtLikeCommentCount = (TextView) view
				.findViewById(R.id.txtLikeCOmmentCount);
		final ImageView imgLikeSmall = (ImageView) view
				.findViewById(R.id.imageLikeSmall);
		final TextView txtThich = (TextView) view.findViewById(R.id.txtThich);
		final TextView txtBoThich = (TextView) view
				.findViewById(R.id.txtBoThich);
		if (comment.isUser_likes()) {
			txtThich.setVisibility(View.GONE);
		} else {
			txtBoThich.setVisibility(View.GONE);
		}
		if (comment.getLike_count() > 0) {
			imgLikeSmall.setVisibility(View.VISIBLE);
			txtLikeCommentCount.setVisibility(View.VISIBLE);
			txtLikeCommentCount.setText(comment.getLike_count() + "");
		} else {
			imgLikeSmall.setVisibility(View.GONE);
			txtLikeCommentCount.setVisibility(View.GONE);
		}
		TextView txtTimeStamp = (TextView) view.findViewById(R.id.txtTimestamp);
		userprofile.setPresetSize(ProfilePictureView.SMALL);
		userprofile.setProfileId(comment.getUser().getId());
		txtUser.setText(comment.getUser().getName());
		txtComment.setText(comment.getMessage());
		Log.e("", "time stampl " + comment.getCreated_time());
		String timeStampt = convertTimeStamp(comment.getCreated_time());

		txtTimeStamp.setText(timeStampt);
		txtThich.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("", "comment id" + comment.getId());
				if (!Session.getActiveSession().isOpened()) {
					showLoginFaceBookDialog();
					// make request to the /me API
				} else {
					if (CommonUtils.checkNetworkAvaliable(CommentActivity.this)) {
						Request request = new Request(Session
								.getActiveSession(), "/" + comment.getId()
								+ "/likes", null, HttpMethod.POST,
								new Callback() {

									@Override
									public void onCompleted(Response response) {
										// TODO Auto-generated method stub
										Log.e("",
												"res like "
														+ response.toString());
										Gson gson = new Gson();
										GraphObject graphObject = response
												.getGraphObject();
										JSONObject json = graphObject
												.getInnerJSONObject();
										Log.e("", "json " + json.toString());
										try {

											boolean state = json
													.getBoolean("FACEBOOK_NON_JSON_RESULT");
											if (state) {
												txtBoThich
														.setVisibility(View.VISIBLE);
												comment.setLike_count(comment
														.getLike_count() + 1);
												imgLikeSmall
														.setVisibility(View.VISIBLE);
												txtLikeCommentCount
														.setVisibility(View.VISIBLE);
												txtLikeCommentCount.setText(comment
														.getLike_count() + "");
												txtThich.setVisibility(View.GONE);
											}
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
						RequestAsyncTask asyncTask = new RequestAsyncTask(
								request);
						asyncTask.execute();
					}
					// showMessageDialog(R.string.error_connection,
					// R.string.error_connection_msg);

				}
			}
		});

		txtBoThich.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("", "comment id" + comment.getId());
				if (!Session.getActiveSession().isOpened()) {
					showLoginFaceBookDialog();
					// make request to the /me API
				} else {
					if (CommonUtils.checkNetworkAvaliable(CommentActivity.this)) {
						Request request = new Request(Session
								.getActiveSession(), "/" + comment.getId()
								+ "/likes", null, HttpMethod.DELETE,
								new Callback() {

									@Override
									public void onCompleted(Response response) {
										// TODO Auto-generated method stub
										Log.e("",
												"res dislike "
														+ response.toString());
										Gson gson = new Gson();
										GraphObject graphObject = response
												.getGraphObject();
										JSONObject json = graphObject
												.getInnerJSONObject();
										try {
											boolean state = json
													.getBoolean("FACEBOOK_NON_JSON_RESULT");
											if (state) {
												txtBoThich
														.setVisibility(View.GONE);
												txtThich.setVisibility(View.VISIBLE);
												comment.setLike_count(comment
														.getLike_count() - 1);
												if (comment.getLike_count() > 0) {
													imgLikeSmall
															.setVisibility(View.VISIBLE);
													txtLikeCommentCount
															.setVisibility(View.VISIBLE);
													txtLikeCommentCount.setText(comment
															.getLike_count());
												} else {
													imgLikeSmall
															.setVisibility(View.GONE);
													txtLikeCommentCount
															.setVisibility(View.GONE);
												}
											}
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
						RequestAsyncTask asyncTask = new RequestAsyncTask(
								request);
						asyncTask.execute();
					} else
						showMessageDialog(R.string.error_connection,
								R.string.error_connection_msg);

				}
			}
		});
		linearLayout.addView(view);
	}

	private String convertTimeStamp(String created_time) {
		// TODO Auto-generated method stub
		Integer[] integers = new Integer[] { 315360000, 31536000, 2628000,
				604800, 86400, 3600, 60, 1 };
		String[] strings = new String[] { "decade", "year", "month", "week",
				"day", "hour", "minute", "second" };
		HashMap<String, Integer> array = new HashMap<String, Integer>();
		array.put("decade", 315360000);
		array.put("year", 31536000);
		array.put("month", 2628000);
		array.put("week", 604800);
		array.put("day", 86400);
		array.put("hour", 3600);
		array.put("minute", 60);
		array.put("second", 0);
		SimpleDateFormat format = new SimpleDateFormat(
				"yyyy-MM-dd'T'HH:mm:ssZZZZ");
		try {
			Date createDate = format.parse(created_time);
			long datediff = new Date().getTime() / 1000 - createDate.getTime()
					/ 1000;
			Log.e("", "datediff " + datediff);
			if (datediff > integers[0]) {
				return " -" + datediff / integers[0] + " thap ky truoc";
			} else if (datediff > integers[1]) {
				return " -" + datediff / integers[1] + " nam truoc";
			} else if (datediff > integers[2]) {
				return " " + datediff / integers[2] + " thang truoc";
			} else if (datediff > integers[3]) {
				return " -" + datediff / integers[3] + " tuan truoc";
			} else if (datediff > integers[4]) {
				return " -" + datediff / integers[4] + " ngay truoc";
			} else if (datediff > integers[5]) {
				return " -" + datediff / integers[5] + " gio truoc";
			} else if (datediff > integers[6]) {
				return " -" + datediff / integers[6] + " phut truoc";
			} else if (datediff >= integers[7]) {
				return " -" + "vua xong";
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		this.menu = menu;
		return true;
	}

	public boolean isFBActive() {
		Session session = Session.getActiveSession();
		if (session == null) {
			return false;
		}
		return session.isOpened();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if (isFBActive()) {
			if (graphUser != null && menu != null)
				menu.getItem(0).getSubMenu().getItem(0)
						.setTitle(getResources().getString(R.string.hello)+ graphUser.getUsername());

		} else {
			menu.getItem(0).getSubMenu().getItem(0).setEnabled(true);
		}
		try {
			if (getSharedPreferences("kenh18cong", 0).getBoolean(
					"notification", true)) {
				menu.getItem(0).getSubMenu().getItem(2)
				.setTitle(getResources().getString(R.string.baoanhmoi)+"("+getResources().getString(R.string.show_notifi)+")");
			} else {
				menu.getItem(0).getSubMenu().getItem(2)
				.setTitle(getResources().getString(R.string.baoanhmoi)+"("+getResources().getString(R.string.show_notifi)+")");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.login:
			if (graphUser == null) {
				Session session = Session.getActiveSession().openActiveSession(
						this, true, callback);
				return true;
			}
		case R.id.favorite:
			Intent intent = new Intent(CommentActivity.this,
					FavoriteActivity.class);
			startActivity(intent);
			return true;
			
			
		case R.id.notification:
			String msg = "";
			if (getSharedPreferences("kenh18cong", 0).getBoolean(
					"notification", true)) {
				msg = getResources().getString(R.string.tatbaoanhmoi);
			} else {
				msg = getResources().getString(R.string.batbaoanhmoi);
			}

			AlertDialog.Builder builder1 = new Builder(CommentActivity.this);
			builder1.setTitle(getResources().getString(R.string.cauhinh))
					.setMessage(msg)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									if (getSharedPreferences("kenh18cong", 0)
											.getBoolean("notification", true)) {
										getSharedPreferences("kenh18cong", 0)
												.edit()
												.putBoolean("notification",
														false).commit();
									} else {
										getSharedPreferences("kenh18cong", 0)
												.edit()
												.putBoolean("notification",
														true).commit();
									}
									onPrepareOptionsMenu(menu);

								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			AlertDialog dialog1 = builder1.create();
			dialog1.show();
			return true;
		case R.id.dowload:
			Intent intent1 = new Intent();
			intent1.setAction(Intent.ACTION_VIEW);
			intent1.addCategory(Intent.CATEGORY_BROWSABLE);
			intent1.setData(Uri.parse(MainActivity.GOOGLE_LINK));
			startActivity(intent1);
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initPhoto(Response response) {
		Log.e("", "res " + response.toString());
		photo = new Photo();
		dismissProgressDialog();
		contentLayout.setVisibility(View.VISIBLE);
		Gson gson = new Gson();
		try {
			GraphObject graphObject = response.getGraphObject();
			if (graphObject != null) {
				JSONObject grap = graphObject.getInnerJSONObject();
				String name = grap.getString("name");
//				for (String string : CommonStatic.avoid_strings) {
//					if (name.contains(string)) {
//						Log.e("",
//								"apear need dellete string "
//										+ string
//										+ "  delete them ");
//						name = name.replace(string,
//								"");
//					}
//				}
				ArrayList<Image> images = new ArrayList<Image>();
				JSONArray imgArray = grap.getJSONArray("images");
				for (int j = 0; j < imgArray.length(); j++) {
					JSONObject object2 = imgArray.getJSONObject(j);
					Image image = gson
							.fromJson(object2.toString(), Image.class);
					// Log.d("image", "image Link " + image.getSource());
					images.add(image);
				}
				JSONObject fromJsonObject = grap.getJSONObject("from");
				User user_post = gson.fromJson(fromJsonObject.toString(),
						User.class);
				photo.setUser_post(user_post);
				photo.setName(name);
				photo.setImages(images);
				if (!grap.isNull("comments")) {
					JSONObject commentJson = grap.getJSONObject("comments");
					JSONObject pagingCOmmentJS = commentJson
							.getJSONObject("paging");
					Paging pagingCOmment = gson.fromJson(
							pagingCOmmentJS.toString(), Paging.class);
					pagingCOmment.rebbuildPagingCommentString();
					photo.setCommentPaging(pagingCOmment);
					JSONArray commentArray = commentJson.getJSONArray("data");
					ArrayList<Comment> comments = new ArrayList<Comment>();
					for (int j = 0; j < commentArray.length(); j++) {
						JSONObject object2 = commentArray.getJSONObject(j);
						Comment comment = gson.fromJson(object2.toString(),
								Comment.class);
						JSONObject object3 = object2.getJSONObject("from");
						User user = gson.fromJson(object3.toString(),
								User.class);
						comment.setUser(user);
						comments.add(comment);
					}
					photo.setList_comments(comments);
					photo.setIs_user_like(is_user_like);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (photo != null && photo.getList_comments() != null) {
			imageLoader.displayImage(photo.getImages().get(0).getSource(),
					imgPhoto, options);
			txtContent.setText(photo.getName());
			if (photo.isIs_user_like()) {
				txtUserLike.setVisibility(View.VISIBLE);
			}
			txtLikeCount.setText(like_count + " nguoi");
			for (Comment comment : photo.getList_comments()) {
				loadViewComment(comment);
			}
		}

	}

	public void dismissProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}

	public void showProgressDialog() {
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(getResources().getString(R.string.dangtaidulieu));
		progressDialog.show();
	}

}
